package com.lxm.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctc.wstx.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;

/**
 * @author ：Administrator
 * @date :创建时间 2021/12/24 16:39
 */
public class HttpUtils {
    static private final Logger logger = LoggerFactory.getLogger(HttpUtils.class);


    static public JSONObject post(String url, String body) {
        HttpClient httpClient = HttpClient.newHttpClient();
        HttpRequest build = HttpRequest.newBuilder(URI.create(url)).POST(HttpRequest.BodyPublishers.ofString(body))
                .header("Content-Type", "application/json").build();
        try {
            HttpResponse<String> send = httpClient.send(build, HttpResponse.BodyHandlers.ofString());
            if (Objects.nonNull(send) && !send.body().isEmpty()) {
                return JSON.parseObject(send.body());
            }
        } catch (Exception e) {
            logger.info("http请求异常:{}", e);
            return null;
        }
        return null;
    }

    static public JSONObject get(String url, JSONObject queryParam) {
        if (!queryParam.isEmpty()) {
            url = url + "?";
            Set<String> strings = queryParam.keySet();
            Iterator<String> iterator = strings.iterator();
            StringBuilder urlBuilder = new StringBuilder(url);
            while (iterator.hasNext()) {
                String next = iterator.next();
                urlBuilder.append(next).append("=").append(queryParam.getString(next)).append("&");
            }
            url = urlBuilder.toString();
            url = url.substring(0, url.length() - 1);

        }
        System.out.println(url);
        HttpClient httpClient = HttpClient.newHttpClient();
        HttpRequest build = HttpRequest.newBuilder(URI.create(url)).GET()
                .header("Content-Type", "application/json").build();
        try {
            HttpResponse<String> send = httpClient.send(build, HttpResponse.BodyHandlers.ofString());
            if (Objects.nonNull(send) && !send.body().isEmpty()) {
                return JSON.parseObject(send.body());
            }
        } catch (Exception e) {
            logger.info("http请求异常:{}", e);
            return null;
        }
        return null;
    }
}
